//
//  ZHealthDetailedViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/21.
//  Copyright © 2017年 zjq. All rights reserved.
//
typedef NS_ENUM(NSInteger,CellType){
    
    CellTypeWithDefualt = 0,
    CellTypeWithAge,
    CellTypeWithPhoneNumber
};
#import "ZHealthDetailedViewController.h"
#import "ZNewBuiltTableViewCell.h"
#import "ZHealhMidTableViewCell.h"
#import "ZHealthBottomTableViewCell.h"
#import "ZHealhTopTableViewCell.h"
#import "ZHMidTFTableViewCell.h" // 带输入框的cell
#import "LZSelectSexView.h" // 性别选择
#import "LZSelectView.h" // 头像选择
#import "JTTakeAlbumOrCamera.h"
#import "ZCullingViewController.h"
#import "LPopChangView.h"
#import "LZHealthDetailModel.h"

static NSString * const KBuiltTableViewCellIdentifier = @"KBuiltTableViewCellIdentifier";
static NSString * const KHealhTopTableViewCellIdentifier = @"KHealhTopTableViewCellIdentifier";
static NSString * const KHealhMidTableViewCellIdentifier = @"KHealhMidTableViewCellIdentifier";
static NSString * const KZHealthBottomTableViewCellIdentifier = @"KZHealthBottomTableViewCellIdentifier";
static NSString * const KZHMTFIdentifier = @"KZHMTFIdentifier";
@interface ZHealthDetailedViewController ()<UITableViewDelegate,UITableViewDataSource,pointOutDelegate,selectSexDelegate,ZCullingViewControllerDelegate> {
    UITableView * _mainTableView;
    NSArray * _titleName;
    NSArray * _contentext;
    NSArray * _styleName;
    LZUserInfo *userInfo;
   
}
@property (nonatomic,strong)LZSelectView * iconSelectView; //选择头像
@property (nonatomic,strong) LZSelectSexView * selectSexView;//选择性别
@property (nonatomic,strong) LPopChangView * lPopChangView;
/** 整个详情模型 */
@property (nonatomic, strong) LZHealthDetailModel *lzHealthDetailModel;
/** 修改头像以后接头像 */
@property (nonatomic, strong) NSString *pic;
@end

@implementation ZHealthDetailedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
    [_mainTableView.mj_header beginRefreshing];
    
}
- (void)initialzeDatas {
    _titleName = @[@"名称",@"性别",@"年龄"];
    _contentext = @[@"自己",@"男",@"22"];
    _styleName = @[@"发病部位照片",@"病例报告照片",@"X光照片"];
    userInfo = [LZUserInfo getUserInfo];
    
}

- (void)initlizeInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.sectionFooterHeight = 0;
    _mainTableView.sectionHeaderHeight = 0;
    _mainTableView.showsVerticalScrollIndicator = NO;
    [_mainTableView registerClass:[ZHealhMidTableViewCell class] forCellReuseIdentifier:KHealhMidTableViewCellIdentifier];
    [_mainTableView registerClass:[ZHealthBottomTableViewCell class] forCellReuseIdentifier:KZHealthBottomTableViewCellIdentifier];
    [_mainTableView registerClass:[ZHealhTopTableViewCell class] forCellReuseIdentifier:KHealhTopTableViewCellIdentifier];
    [_mainTableView registerClass:[ZHMidTFTableViewCell class] forCellReuseIdentifier:KZHMTFIdentifier];
    [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"nothing"];
    [self.view addSubview:_mainTableView];
    [_mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 下拉刷新
    __weak typeof(self) weakSelf = self;
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [_mainTableView.mj_header endRefreshing];
    }];
    
}
//表格视图协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 3;
    }else if (section == 2) {
        return 4;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 60*ysIZE;
    }else if (indexPath.section == 1) {
        return 65*ysIZE;
    }else if (indexPath.section ==2) {
        if (indexPath.row == 0 ) {
            return 45*ysIZE;
        }else{
            return 90*ysIZE;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10*ysIZE;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZHealhTopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KHealhTopTableViewCellIdentifier forIndexPath:indexPath];
        cell.titlelabel.text = @"头像";
        //cell.headImageView.image = [UIImage imageNamed:@"data_tx_140"];
        // 头像赋值
        NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,_lzHealthDetailModel.pic];
        [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"icon_center_tx"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1) {
        ZHealhMidTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KHealhMidTableViewCellIdentifier forIndexPath:indexPath];
        cell.titleName.text = _titleName[indexPath.row];
        if (indexPath.row == 0) {
            cell.bottomLabel.text = _lzHealthDetailModel.title;
        }else if (indexPath.row == 1) {
            cell.bottomLabel.text = _lzHealthDetailModel.sex;
        }else {
            cell.bottomLabel.text = _lzHealthDetailModel.age;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
             ZHealhTopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KHealhTopTableViewCellIdentifier forIndexPath:indexPath];
            cell.headImageView.hidden = YES;
            cell.titlelabel.text = @"档案照片";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            ZHealthBottomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KZHealthBottomTableViewCellIdentifier forIndexPath:indexPath];
            cell.styleLabel.text = _styleName[indexPath.row-1];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            // 发病部位照片
            if (indexPath.row == 1) {
                NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,_lzHealthDetailModel.part];
                [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"Reference_picture"]];
                // 数量
                if (_lzHealthDetailModel.part_num) {
                    cell.numberLabel.text = [NSString stringWithFormat:@"%@张照片",_lzHealthDetailModel.part_num];
                }
                
            }else if (indexPath.row == 2) {
                // 病例报告照片
                NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,_lzHealthDetailModel.report];
                [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"Reference_picture"]];
                // 数量
                if (_lzHealthDetailModel.report_num) {
                    cell.numberLabel.text = [NSString stringWithFormat:@"%@张照片",_lzHealthDetailModel.report_num];
                }
                
            }else {
                // X光照片
                NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,_lzHealthDetailModel.xray];
                [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"Reference_picture"]];
                // 数量
                if (_lzHealthDetailModel.xray_num) {
                    cell.numberLabel.text = [NSString stringWithFormat:@"%@张照片",_lzHealthDetailModel.xray_num];
                }
            }
            return cell;
        }
    }
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"nothing" forIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        [self ejectIconView];
        return;
    }else if (indexPath.section == 1 && indexPath.row == 1){
        [self ejectsexView];
        return;
    }else if (indexPath.section == 2&& !(indexPath.row == 0)) {
        
        if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
            [YJProgressHUD showMessage:@"没有网络" inView:self.view];
            return;
        }
        
    ZCullingViewController * ZCVC = [[ZCullingViewController alloc] init];
        // 把文档id传过去
        ZCVC.fileID = _lzHealthDetailModel.fileID;
        ZCVC.userID = userInfo.uid;
        ZCVC.delegate = self;
//        ZCVC.freshBlock = ^ {
//            [self pullDownData];
//        };
        
        switch (indexPath.row) {
            case 1:
                ZCVC.type = @"1";
                break;
            case 2:
                ZCVC.type = @"2";
                break;
            case 3:
                ZCVC.type = @"3";
                break;
                
            default:
                break;
        }
    [self.navigationController pushViewController:ZCVC animated:YES];
    return;
    }else if (indexPath.section == 1&& indexPath.row == 0) {
        [self changItemWithName:@"修改姓名" indexPath:indexPath keyBoradType:UIKeyboardTypeDefault cellType:CellTypeWithDefualt];
    }else if (indexPath.section == 1 && indexPath.row ==  2) {
         [self changItemWithName:@"修改年龄" indexPath:indexPath keyBoradType:UIKeyboardTypeNumberPad cellType:CellTypeWithAge];
    }
    return;
}
// 弹出选择界面的方法
- (void)ejectIconView {
    [self.view endEditing:YES];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.iconSelectView];
}
- (void)ejectsexView {
    [self.view endEditing:YES];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.selectSexView];

}
// 选择头像来选的方法
- (void)SelectCellIndexPath:(NSInteger)cellSection index:(NSInteger)cellIndex {
    if (cellSection == 0&&cellIndex==0) {
       [JTTakeAlbumOrCamera takeAlbumWithViewcontroller:self withID:self];
        return;
    }else if (cellSection == 0 && cellIndex == 1) {
         [JTTakeAlbumOrCamera takeCameraWithViewcontroller:self withID:self];
        return;
    }else{
        
        return;
    }
}
// 弹窗修改 年龄和名字
- (void)changItemWithName:(NSString *)itemName indexPath:(NSIndexPath *)indexPath keyBoradType:(UIKeyboardType)type cellType:(CellType)cellType {
    LPopChangView *changeView = [[LPopChangView alloc] initWithFrame:self.navigationController.view.bounds AndTitle:[NSString stringWithFormat:@"%@",itemName] type:type];
    [self.navigationController.view addSubview:changeView];
    
    __weak typeof(changeView) weakChangeView = changeView;
    changeView.InputContentBlock = ^(NSString *inputContent){
        if (!inputContent.length) {
            [YJProgressHUD showMessage:@"输入不能为空" inView:self
             .navigationController.view];
            return;
        }
        switch (indexPath.row) {
            case 0:// 姓名
                [self requestWithName:inputContent];
                break;
            case 1:
                
                break;
            case 2:// 年龄
                [self requestWithAge:inputContent];
                NSInteger age = [inputContent intValue];
                if (age <= 0 || age >= 100) {
                    [YJProgressHUD showMessage:@"年龄输入有误" inView:self.navigationController.view];
                    return;
                }
                break;
                
            default:
                break;
        }
        if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
            [weakChangeView removeFromSuperview];
            return;
        }else {
            ZHealhMidTableViewCell * cell = [_mainTableView cellForRowAtIndexPath:indexPath];
            cell.bottomLabel.text = inputContent;
            [weakChangeView removeFromSuperview];
        }
        
    };
}


// 选择性别的方法
- (void)selectSEX:(NSString *)sex cellIndex:(NSInteger)cellIndex {
    if (cellIndex == 1 ) {
        [self.selectSexView removeFromSuperview];
        return;
    }else {
        NSLog(@"%@",sex);
        [self requestWithSex:sex];
    }
}
- (LZSelectSexView *)selectSexView {
    if (_selectSexView) {
        return _selectSexView;
    }
    _selectSexView = [[LZSelectSexView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _selectSexView.pointDeleGate = self;
    return _selectSexView;
}

- (LZSelectView *)iconSelectView {
    if (_iconSelectView) {
        return _iconSelectView;
    }
    _iconSelectView = [[LZSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _iconSelectView.pointDeleGate = self;
    return _iconSelectView;
}

// 选中照片回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // UIImagePickerControllerOriginalImage 原始图片
    // UIImagePickerControllerEditedImage 编辑后图片
    UIImage *icon = info[UIImagePickerControllerEditedImage];
    // 换头像以后网络请求
    [self requestWithIcon:icon];
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}
// 修改头像
- (void)requestWithIcon:(UIImage *)icon {
    
    if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
        return;
    }
    NSDictionary *paramas = @{@"id":_lzHealthDetailModel.fileID};
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithObject:icon forKey:@"pic"];
    
    
    
    [BaseRequest requestWithMethodForFile:TestURL paramars:paramas paramarsSite:@"File/editFile" fileDict:dict1 progressBlock:nil successBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"-------修改头像返回数据--------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改头像失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
             //拿到新换的照片转存为字符串
            _lzHealthDetailModel.pic = dict[@"list"][@"pic"];
            NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
//            ZHealhTopTableViewCell *cell = [_mainTableView cellForRowAtIndexPath:index];
//            NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,_lzHealthDetailModel.pic];
//            [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"icon_center_tx"]];
             [_mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationNone];
            [YJProgressHUD showMessage:@"修改头像成功" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
    
}

// 修改姓名
- (void)requestWithName:(NSString *)name {
    if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
        
        return;
    }
    
    NSString * stringName = [name stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
    
    NSDictionary *paramas = @{@"id": _lzHealthDetailModel.fileID,@"title":stringName};
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/editFile" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改名字失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改名字成功" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
}

// 修改性别
- (void)requestWithSex:(NSString *)sex {
    if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
        return;
    }
    
    NSDictionary *paramas = @{@"id": _lzHealthDetailModel.fileID,@"sex":sex};
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/editFile" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"------修改性别-------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改性别失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改性别成功" inView:self.view];
            _lzHealthDetailModel.sex = dict[@"list"][@"sex"];
            
            NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:1];
            [_mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
        
    }];
}

// 修改年龄
- (void)requestWithAge:(NSString *)age {
    if (!_lzHealthDetailModel.fileID || [_lzHealthDetailModel.fileID isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
        return;
    }
    
    NSDictionary *paramas = @{@"id": _lzHealthDetailModel.fileID,@"age":age};
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/editFile" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"修改年龄失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"修改年龄成功" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"修改失败" inView:self.view];
    }];
}

// 下拉刷新方法
- (void)pullDownData {
    __weak typeof(self) weakSelf = self;
    NSDictionary *paramas = @{@"uid":userInfo.uid,@"id":self.fileID};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/fileDetails" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"----------档案详情数据----------%@",dict);
        if ([dict[@"code"] intValue]==1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealPullDownDataWithDict:dict];
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"记载失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
    }];
}

// 处理下拉刷新数据
- (void)dealPullDownDataWithDict:(NSDictionary *)dict {
    NSDictionary *tempDict = dict[@"list"];
        // 中间部分
        LZHealthDetailModel *lzHealthDetailModel = [[LZHealthDetailModel alloc] initWithDict:[tempDict mutableCopy]];
    self.lzHealthDetailModel = lzHealthDetailModel;
    [_mainTableView reloadData];
}

- (void)refreshCollectionView {
    [self pullDownData];
}

- (void)setFileID:(NSString *)fileID {
    _fileID = fileID;
    [_mainTableView.mj_header beginRefreshing];
}



@end
